package ru.efimmatytsin.tweeterella.services.impl;

import org.springframework.stereotype.Repository;
import ru.efimmatytsin.tweeterella.entities.Photo;
import ru.efimmatytsin.tweeterella.entities.User;
import ru.efimmatytsin.tweeterella.services.PhotoService;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.List;

/**
 * Created by Efim Matytsin on 17.02.15.
 */
@Repository
public class PhotoServiceImpl implements PhotoService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Photo getPhoto(BigInteger id) {
        return entityManager.find(Photo.class,id);
    }

    @Override
    public Photo savePhoto(Photo photo) {
        entityManager.persist(photo);
        return photo;
    }

    @Override
    public List<Photo> getAllPhotos() {
        Query query = entityManager.createQuery("SELECT e FROM Photo e");
        return (List<Photo>) query.getResultList();
    }

    @Override
    public List<Photo> getUserPhotos(User user) {
        Query query = entityManager.createQuery("SELECT e FROM Photo e WHERE e.owner=:user");
        query.setParameter("user",user);
        return (List<Photo>) query.getResultList();
    }
}
